package com.al.repository;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBHelper {
	private Connection connection = null;
	private Statement statement = null;
	private ResultSet resultSet = null;
	private static final String URL = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
	private static final String USER = "root";
	private static final String  PASSWD = "";
	
	//static 只加载一次
	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	//建立连接
	private void getConnection() {
		try {
			connection = DriverManager.getConnection(URL, USER, PASSWD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//查询
	public ResultSet executeQuery(String sql) throws Exception{
		this.getConnection();
		statement = connection.createStatement();
		resultSet = statement.executeQuery(sql);
		return resultSet;
	}
	//修改
	public void executeUpdate(String sql) throws Exception{
		this.getConnection();
		statement = connection.createStatement();
		statement.executeUpdate(sql);
	}
	
	//释放资源
	public void close() throws Exception{
		if(resultSet != null) {
			resultSet.close();
			resultSet = null;
		}
		if(statement != null) {
			statement.close();
			statement = null;
		}
		if(connection != null) {
			connection.close();
			connection = null;
		}
	}

}
